package com.example.educationai.service;

import com.example.educationai.entity.User;
import com.example.educationai.entity.UserRole;
import com.example.educationai.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public User register(User user) {
        log.debug("开始注册用户: {}", user.getUsername());
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 设置默认角色
        user.setRole(UserRole.ROLE_USER);
        
        // 保存用户
        User savedUser = userRepository.save(user);
        log.debug("用户注册成功: {}", savedUser.getUsername());
        
        return savedUser;
    }

    @Override
    public User findByUsername(String username) {
        log.debug("查找用户: {}", username);
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在: " + username));
    }

    @Override
    public User findByEmail(String email) {
        log.debug("通过邮箱查找用户: {}", email);
        return userRepository.findByEmail(email)
                .orElseThrow(() -> new RuntimeException("邮箱不存在: " + email));
    }

    @Override
    public boolean existsByUsername(String username) {
        return userRepository.existsByUsername(username);
    }

    @Override
    public boolean existsByEmail(String email) {
        return userRepository.existsByEmail(email);
    }
} 